<template>
  <div class="dashboard">
    <!-- 统计卡片 -->
    <el-row :gutter="20">
      <el-col :xs="24" :sm="12" :md="6" v-for="stat in stats" :key="stat.title">
        <el-card class="stat-card" :loading="stat.loading || loading">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: stat.color }">
              <el-icon :size="30">
                <component :is="stat.icon" />
              </el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value" :class="stat.valueClass">{{ stat.value }}</div>
              <div class="stat-title">{{ stat.title }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 日志统计 -->
    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :xs="24" :sm="24" :md="24">
        <el-card :loading="statsLoading">
          <template #header>
            <div class="card-header">
              <span>日志统计</span>
              <el-button text type="primary" @click="refreshLogStats">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </template>
          <div class="log-stats">
            <el-row :gutter="20">
              <el-col :xs="12" :sm="6" :md="6">
                <div class="stat-item">
                  <div class="stat-label">总日志数</div>
                  <div class="stat-number">{{ formatNumber(logStats.total || 0) }}</div>
                </div>
              </el-col>
              <el-col :xs="12" :sm="6" :md="6">
                <div class="stat-item">
                  <div class="stat-label">错误日志</div>
                  <div class="stat-number error">{{ formatNumber(getErrorCount()) }}</div>
                </div>
              </el-col>
              <el-col :xs="12" :sm="6" :md="6">
                <div class="stat-item">
                  <div class="stat-label">今日日志</div>
                  <div class="stat-number">{{ formatNumber(logStats.todayCount || 0) }}</div>
                </div>
              </el-col>
              <el-col :xs="12" :sm="6" :md="6">
                <div class="stat-item">
                  <div class="stat-label">API日志</div>
                  <div class="stat-number">{{ formatNumber(getApiCount()) }}</div>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="20" style="margin-top: 20px">
              <el-col :xs="24" :sm="12" :md="12">
                <div class="stat-item">
                  <div class="stat-label">日志类型分布</div>
                  <div class="stat-tags">
                    <el-tag v-for="typeStat in logStats.typeStats" :key="typeStat.type" size="small" style="margin-right: 8px; margin-bottom: 4px">
                      {{ typeStat.type }}: {{ formatNumber(typeStat.count) }}
                    </el-tag>
                  </div>
                </div>
              </el-col>
              <el-col :xs="24" :sm="12" :md="12">
                <div class="stat-item">
                  <div class="stat-label">日志级别分布</div>
                  <div class="stat-tags">
                    <el-tag v-for="levelStat in logStats.levelStats" :key="levelStat.level" :type="getLogLevelType(levelStat.level)" size="small" style="margin-right: 8px; margin-bottom: 4px">
                      {{ levelStat.level }}: {{ formatNumber(levelStat.count) }}
                    </el-tag>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 最近日志 -->
    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>最近日志</span>
              <div style="display: flex; align-items: center; gap: 10px">
                <el-switch
                  v-model="autoRefreshEnabled"
                  active-text="自动刷新"
                  inactive-text=""
                  @change="handleAutoRefreshChange"
                />
                <el-button text type="primary" @click="refreshLogs">
                  <el-icon><Refresh /></el-icon>
                  刷新
                </el-button>
              </div>
            </div>
          </template>
          <el-table :data="recentLogs" style="width: 100%" :loading="logsLoading">
            <el-table-column prop="message" label="日志内容" show-overflow-tooltip />
            <el-table-column prop="level" label="级别" width="80">
              <template #default="{ row }">
                <el-tag :type="getLogLevelType(row.level)" size="small">
                  {{ row.level }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="type" label="类型" width="80" />
            <el-table-column prop="created_at" label="时间" width="180">
              <template #default="{ row }">
                {{ formatDate(row.created_at) }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { getUserList } from '@/api/users'
import { getPermissionList } from '@/api/permissions'
import { getLogList, getLogStats } from '@/api/logs'
import { getBackupList } from '@/api/backups'
import { checkHealth } from '@/api/health'
import type { LogData, LogStatsResponse } from '@/api/logs'
import type { HealthCheckData } from '@/api/health'
import { Refresh } from '@element-plus/icons-vue'
import { formatDate, utils } from '@/utils'

const loading = ref(false)
const logsLoading = ref(false)
const statsLoading = ref(false)
const autoRefreshEnabled = ref(false) // 自动刷新开关，默认关闭
let autoRefreshTimer: number | null = null // 自动刷新定时器

// 统计数据
const stats = ref([
  { title: '总用户数', value: '0', icon: 'User', color: '#409eff', loading: false, valueClass: '' },
  { title: '权限总数', value: '0', icon: 'Avatar', color: '#67c23a', loading: false, valueClass: '' },
  { title: '备份数量', value: '0', icon: 'FolderOpened', color: '#e6a23c', loading: false, valueClass: '' },
  { title: '系统健康', value: '检查中', icon: 'Monitor', color: '#909399', loading: false, valueClass: '' }
])

// 最近日志
const recentLogs = ref<LogData[]>([])

// 健康检查状态
const healthStatus = ref<HealthCheckData>({
  status: 'unhealthy',
  checks: {},
  timestamp: ''
})

// 日志统计
const logStats = ref<LogStatsResponse>({
  total: 0,
  typeStats: [],
  levelStats: [],
  todayCount: 0
})

// 加载统计数据
const loadStats = async () => {
  loading.value = true
  try {
    // 并行加载所有统计数据
    const [usersRes, permissionsRes, backupsRes, healthRes] = await Promise.allSettled([
      getUserList({ page: 1, pageSize: 1 }),
      getPermissionList({ page: 1, pageSize: 1 }),
      getBackupList({ page: 1, pageSize: 1 }),
      checkHealth()
    ])

    // 更新用户数
    if (usersRes.status === 'fulfilled') {
      stats.value[0].value = formatNumber(usersRes.value.data.total)
    }

    // 更新权限数
    if (permissionsRes.status === 'fulfilled') {
      stats.value[1].value = formatNumber(permissionsRes.value.data.total)
    }

    // 更新备份数
    if (backupsRes.status === 'fulfilled') {
      stats.value[2].value = formatNumber(backupsRes.value.data.total)
    }

    // 更新健康状态
    if (healthRes.status === 'fulfilled') {
      const healthData = healthRes.value.data
      healthStatus.value = healthData
      const isHealthy = healthData.status === 'healthy'
      stats.value[3].value = isHealthy ? '健康' : '异常'
      stats.value[3].color = isHealthy ? '#67c23a' : '#f56c6c'
      stats.value[3].valueClass = isHealthy ? 'text-success' : 'text-danger'
    } else {
      stats.value[3].value = '异常'
      stats.value[3].color = '#f56c6c'
      stats.value[3].valueClass = 'text-danger'
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 加载最近日志
const refreshLogs = async () => {
  logsLoading.value = true
  try {
    const res = await getLogList({ page: 1, pageSize: 10 })
    recentLogs.value = res.data.list || []
  } catch (error) {
    console.error('加载最近日志失败:', error)
  } finally {
    logsLoading.value = false
  }
}

// 处理自动刷新开关变化
const handleAutoRefreshChange = (enabled: boolean) => {
  if (enabled) {
    startAutoRefresh()
  } else {
    stopAutoRefresh()
  }
}

// 启动自动刷新
const startAutoRefresh = () => {
  stopAutoRefresh() // 先清除可能存在的定时器
  autoRefreshTimer = window.setInterval(() => {
    refreshLogs()
  }, 5000) // 5秒刷新一次
}

// 停止自动刷新
const stopAutoRefresh = () => {
  if (autoRefreshTimer !== null) {
    clearInterval(autoRefreshTimer)
    autoRefreshTimer = null
  }
}


// 刷新日志统计
const refreshLogStats = async () => {
  statsLoading.value = true
  try {
    // 根据 API 文档，请求体可以是空对象，返回所有日志的统计
    const res = await getLogStats({})
    logStats.value = res.data
  } catch (error) {
    console.error('加载日志统计失败:', error)
  } finally {
    statsLoading.value = false
  }
}

// 获取错误日志数（从 levelStats 中获取 error 级别的数量）
const getErrorCount = (): number => {
  const errorStat = logStats.value.levelStats.find((s: { level: string; count: number }) => s.level === 'error')
  return errorStat ? errorStat.count : 0
}

// 获取 API 日志数（从 typeStats 中获取 api 类型的数量）
const getApiCount = (): number => {
  const apiStat = logStats.value.typeStats.find((s: { type: string; count: number }) => s.type === 'api')
  return apiStat ? apiStat.count : 0
}

// 格式化数字
const formatNumber = (num: number): string => {
  return utils.formatNumber(num)
}

// 获取日志级别类型
const getLogLevelType = (level: string): string => {
  const levelMap: Record<string, string> = {
    error: 'danger',
    warn: 'warning',
    info: 'info',
    debug: ''
  }
  return levelMap[level] || ''
}


// 初始化加载数据
onMounted(() => {
  loadStats() // 这里已经包含了健康检查
  refreshLogs() // 加载最近日志
  // 启动自动刷新
  if (autoRefreshEnabled.value) {
    startAutoRefresh()
  }
  // 日志统计最后加载
  refreshLogStats()
})

// 组件卸载时清理定时器
onUnmounted(() => {
  stopAutoRefresh()
})
</script>

<style scoped lang="scss">
.dashboard {
  .equal-height-row {
    display: flex;
    flex-wrap: wrap;

    .el-col {
      display: flex;
    }
  }

  .equal-height-card {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;

    :deep(.el-card__body) {
      flex: 1;
      display: flex;
      flex-direction: column;
    }
  }

  .stat-card {
    .stat-content {
      display: flex;
      align-items: center;
      gap: 20px;

      .stat-icon {
        width: 60px;
        height: 60px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
      }

      .stat-info {
        flex: 1;

        .stat-value {
          font-size: 24px;
          font-weight: bold;
          color: #303133;
          margin-bottom: 5px;

          &.text-success {
            color: #67c23a;
          }

          &.text-danger {
            color: #f56c6c;
          }
        }

        .stat-title {
          font-size: 14px;
          color: #909399;
        }
      }
    }
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }


  .log-stats {
    .stat-item {
      padding: 15px;
      text-align: center;

      .stat-label {
        font-size: 14px;
        color: #909399;
        margin-bottom: 10px;
      }

      .stat-number {
        font-size: 28px;
        font-weight: bold;
        color: #303133;

        &.error {
          color: #f56c6c;
        }
      }

      .stat-tags {
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
        align-items: center;
        min-height: 40px;
      }
    }
  }
}
</style>

